package com.example.hao.ximalaya.activity;

import android.support.annotation.Nullable;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.hao.ximalaya.R;
import com.example.hao.ximalaya.fragment.BlankFragment;
import com.example.hao.ximalaya.fragment.RecommendFragment;
import com.ogaclejapan.smarttablayout.SmartTabLayout;

public class MainActivity extends AppCompatActivity {

    private SmartTabLayout stl;
    private ViewPager vp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        vp.setCurrentItem(1);

    }

    private void initView() {
        stl = findViewById(R.id.stl);
        vp = findViewById(R.id.vp);
        vp.setAdapter(new PagerAdapter(getSupportFragmentManager()));
        stl.setViewPager(vp);
    }


    class PagerAdapter extends FragmentPagerAdapter {


        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void setPageTitle(String[] pageTitle) {
          this.pageTitle = pageTitle;
        }
        String[] pageTitle = {"分类", "推荐", "VIP", "直播", "小说", "广播", "儿童", "精品", "段子", "音乐", "相声", "历史", "人文", "情感", "英语"};
        Fragment[] fragments = new Fragment[pageTitle.length];

        private int currentIndex= -1;
        public void showFragment(int nextIndex){
            if (currentIndex == nextIndex){
                return;
            }
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

            if (fragments[nextIndex] == null){

            }

            ft.commit();
            currentIndex = nextIndex;
        }


        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return pageTitle[position];
        }

        @Override
        public Fragment getItem(int position) {
            BlankFragment blankFragment = new BlankFragment();
            if (fragments[position] == null) {
                switch (position) {
                    case 1:
                        return fragments[position] = new RecommendFragment();
                    default:
                        Bundle bundle = new Bundle();
                        bundle.putString("title",pageTitle[position]);
                        blankFragment.setArguments(bundle);
                        return fragments[position] = blankFragment;
                }

            }
            return null;
        }

        @Override
        public int getCount() {

            return fragments == null ? 0 : fragments.length;
        }


    }
}
